package com.wan.net.core.tcp;

import com.wan.net.core.packet.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
/**
 * @author wwh
 * @date 2022/6/16 10:57
 */
public class TcpCodec extends ByteToMessageCodec<Packet> {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void encode(ChannelHandlerContext context, Packet pack, ByteBuf byteBuf) throws Exception {
        Channel channel = context.channel();
        try {
            pack.write(byteBuf);
        } catch (Exception e) {
            log.error("TcpCodec encode exception异常!channel:{},pack:{}", channel, pack, e);
            throw e;
        } catch (Throwable e) {
            log.error("TcpCodec encode Throwable异常!channel:{},pack:{}", channel, pack, e);
            throw e;
        }
    }

    @Override
    protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> out) throws Exception {
        Channel channel = context.channel();
        try {
            byteBuf.markReaderIndex();
            Packet packet = new Packet();
            if(packet.read(byteBuf)) out.add(packet);
        } catch (Exception e) {
            log.error("TcpCodec decode exception异常!{}", channel, e);
            throw e;
        } catch (Throwable e) {
            log.error("TcpCodec decode Throwable异常!{}", channel, e);
            throw e;
        }
    }
}
